<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\enum\KsBidEnum;
use app\model\KsProjectBidTaskContentModel;
use app\model\KsProjectBidTaskLogModel;
use app\model\KsProjectBidTaskModel;
use app\service\project\KsBidService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\facade\Cache;

class KsProjectBidEditWork extends BaseWork
{
    protected function configure()
    {
        // 指令配置
        $this->setName('ks_project_bid_edit_work');
        $this->setDescription('修改快手智能托管出价脚本')
            ->addArgument('id', Argument::OPTIONAL, 'id');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $this->getOutputMessage('修改快手智能托管出价开始');
        $redis = Cache::store('redis')->handler();
        $id = $input->getArgument('id');
        if (! $id) {
            $id = $redis->lPop(KsBidEnum::PROJECT_BID_TASK_REDIS_KEY);
        }
        try {
            if (! $id) {
                return;
            }
            $this->getOutputMessage('修改快手智能托管出价id：' . $id . '任务开始');
            $task = KsBidService::getBidTask(intval($id));
            if (! $task instanceof KsProjectBidTaskModel) {
                $this->getOutputMessage('修改快手智能托管出价失败id：' . $id . '任务数据不存在');
                return;
            }
            if ($task->getAttr('status')) {
                $this->getOutputMessage('修改快手智能托管出价id：' . $id . '修改完毕');
                return;
            }
            if ($task->getAttr('is_pull')) {
                $this->getOutputMessage('修改快手智能托管出价id：' . $id . '拉取完毕');
                return;
            }
            // 获取类型
            $content = KsBidService::getBidTaskContent($task);
            $page = 1;
            while (true) {
                // 获取数据
                $pullResult = KsBidService::pullProject($task, $page++);
                if ($pullResult === false) {
                    // 修改状态
                    KsBidService::updateTaskStatus($task, KsBidEnum::TASK_STATUS_FAIL);
                    throw new \Exception('修改快手智能托管出价id:' . $id . '拉取失败:' . KsBidService::getError(0));
                }
                if (! $pullResult) {
                    break;
                }
                foreach ($pullResult as $project) {
                    $projectId = $project['project_id'];
                    $projectName = $project['name'];
                    $project = KsBidService::pullProjectDetail($task, strval($project['project_id']));
                    if (! $project) {
                        // 存错误日志
                        $logData = [
                            'project_id' => $projectId,
                            'project_name' => $projectName,
                            'status' => KsBidEnum::TASK_STATUS_FAIL,
                            'error_json' => '',
                            'error_msg' => KsBidService::getError(0),
                        ];
                        KsBidService::addBidLog($content[0], $logData);
                        throw new \Exception('获取项目数据失败id：' . $id . KsBidService::getError(0));
                    }
                    foreach ($content as $val) {
                        if (KsBidService::isType($project, $val->getAttr('type'))) {
                            // 修改数据
                            if ($val->getAttr('type') != KsBidEnum::TASK_TYPE_FUR) {
                                // 验证出价是否相同不需要修改
                                if ($project['cpa_bid'] == $val->getAttr('cpa_bid') * 1000 && $project['deep_conversion_bid'] == $val->getAttr('deep_conversion_bid') * 1000) {
                                    continue;
                                }
                            } else {
                                // 验证出价是否相同不需要修改
                                if ($project['cpa_bid'] == $val->getAttr('cpa_bid') * 1000) {
                                    continue;
                                }
                            }
                            // 存记录
                            $logData = [];
                            $logData['project_id'] = $projectId;
                            $logData['project_name'] = $projectName;
                            $logData['project_content'] = json_encode($project);
                            $res = KsBidService::addBidLog($val, $logData);
                            if (! $res) {
                                $this->getOutputMessage('日志记录失败' . KsBidService::getError(0));
                            }
                        }
                    }
                }
            }
            // 拉取完成
            $task->setAttr('is_pull', KsProjectBidTaskModel::PULL_SUCCESS);
            if (! (new KsProjectBidTaskLogModel())->where('project_bid_id', '=', $task->getKey())->count()) {
                $task->setAttr('status', KsProjectBidTaskModel::STATUS_SUCCESS);
                (new KsProjectBidTaskContentModel())->where('project_bid_id', $task->getKey())->update(['status' => KsProjectBidTaskModel::STATUS_SUCCESS]);
            }
            $task->save();
            $this->getOutputMessage('修改快手智能托管出价id:' . $id . '拉取完成');
        } catch (\Exception $e) {
            $redis->rPush(KsBidEnum::PROJECT_BID_TASK_REDIS_KEY, $id);
            $this->getOutputMessage('修改快手智能托管出价失败' . $e->getMessage());
        }
        $this->getOutputMessage('修改快手智能托管出价结束');
    }
}
